package com.gitee.wsl.security.encrypt.sample

import com.gitee.wsl.security.encrypt.Encrypt
import com.gitee.wsl.security.encrypt.StringToStringEncrypt

class CurveCipher(val row: Int,val col: Int): StringToStringEncrypt {
    override fun decrypt(src: String): String {
        return with(src) {
            var reverseFlag = col % 2 == 0
            val c = CharArray(length)
            for (i in indices) {
                if (i % row == 0) {
                    reverseFlag = !reverseFlag
                }
                val listIndex = if (reverseFlag) i % row else row - i % row - 1
                c[i / row + listIndex * col] = this[i]
            }
            c.joinToString("").reversed()
        }
    }

    override fun encrypt(src: String): String =
        src.chunked(col).run {
            var reverseFlag = false
            val sb = StringBuilder()
            for (i in src.indices) {
                if (i % row == 0) {
                    reverseFlag = !reverseFlag
                }
                val listIndex = if (reverseFlag) i % row else row - i % row - 1
                sb.append(this[listIndex][i / row])
            }
            sb.reverse().toString()
        }
}

fun Encrypt.Companion.curve(row: Int, col: Int) = CurveCipher(row, col)